# -*- coding: utf-8 -*-
import random
import json
import gevent
from gevent.pool import Pool
from gevent import queue as Queue
import paho.mqtt.client as mqtt

try:
    import setting
except ImportError:
    import sys

    sys.path.append('..')
    import setting

import logging

logger = logging.getLogger('push')

mqtt_Q = Queue.Queue()
MQTT_Prefix = setting.mqtt['prefix']


def push_mqtt(userid, data):
    mqtt_Q.put((MQTT_Prefix + '/user/' + userid + '/push', json.dumps(data)))


def MQTT_worker():
    try:
        client = mqtt.Client(client_id='w06_' + str(random.randint(0, 9999999)))
        client.username_pw_set(setting.mqtt['username'], setting.mqtt['password'])
        client.connect(setting.mqtt['server'], setting.mqtt['port'])
        client.loop_start()
        while True:
            topic, message = mqtt_Q.get()
            client.publish(topic, message, 1)
        client.disconnect()
    except:
        logger.error('MQTT PUSH Faild', exc_info=True)
    finally:
        pool.spawn(MQTT_worker)


pool = Pool(10)
for i in xrange(5):
    gevent.sleep(0.2 * i)
    pool.spawn(MQTT_worker)
